const express = require('express');
const User = require('../models/User');
const Submission = require('../models/Submission');
const { authenticateToken } = require('../middleware/auth');

const router = express.Router();

// 获取用户统计信息
router.get('/stats/overview', authenticateToken, async (req, res) => {
  try {
    const userId = req.user._id;

    // 获取基本统计
    const totalSubmissions = await Submission.countDocuments({ userId });
    const completedSubmissions = await Submission.countDocuments({ 
      userId, 
      status: 'completed' 
    });

    // 获取平均分
    const avgScoreResult = await Submission.aggregate([
      { $match: { userId, status: 'completed', 'scores.overall': { $exists: true } } },
      { $group: { _id: null, avgScore: { $avg: '$scores.overall' } } }
    ]);

    const averageScore = avgScoreResult.length > 0 ? 
      Math.round(avgScoreResult[0].avgScore * 10) / 10 : 0;

    // 获取分数分布
    const scoreDistribution = await Submission.aggregate([
      { $match: { userId, status: 'completed', 'scores.overall': { $exists: true } } },
      { $group: { _id: '$scores.overall', count: { $sum: 1 } } },
      { $sort: { _id: 1 } }
    ]);

    const distribution = {};
    scoreDistribution.forEach(item => {
      distribution[item._id] = item.count;
    });

    // 获取最近7天的趋势
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

    const recentTrend = await Submission.aggregate([
      { 
        $match: { 
          userId, 
          status: 'completed',
          createdAt: { $gte: sevenDaysAgo },
          'scores.overall': { $exists: true }
        } 
      },
      {
        $group: {
          _id: { $dateToString: { format: '%Y-%m-%d', date: '$createdAt' } },
          avgScore: { $avg: '$scores.overall' },
          count: { $sum: 1 }
        }
      },
      { $sort: { _id: 1 } }
    ]);

    res.json({
      success: true,
      data: {
        totalSubmissions,
        completedSubmissions,
        averageScore,
        scoreDistribution: distribution,
        recentTrend: recentTrend.map(item => ({
          date: item._id,
          score: Math.round(item.avgScore * 10) / 10,
          count: item.count
        }))
      }
    });
  } catch (error) {
    console.error('获取统计信息错误:', error);
    res.status(500).json({
      success: false,
      message: '获取统计信息失败'
    });
  }
});

module.exports = router;
